import { JwtModule, JwtModuleOptions } from '@nestjs/jwt';
import { ConfigModule, ConfigService } from '@nestjs/config';
import type { StringValue } from 'ms';

interface JwtConfig {
  secret: string;
  expiresIn: string;
  issuer?: string;
  audience?: string;
  algorithm: string;
}

/**
 * JWT 模块配置
 * 全局注册，所有模块都可以直接使用 JwtService
 */
export default JwtModule.registerAsync({
  imports: [ConfigModule],
  inject: [ConfigService],
  useFactory: (configService: ConfigService): JwtModuleOptions => {
    const jwtConfig = configService.get<JwtConfig>('jwt');

    const algorithm =
      (jwtConfig?.algorithm as
        | 'HS256'
        | 'HS384'
        | 'HS512'
        | 'RS256'
        | 'RS384'
        | 'RS512') || 'HS256';

    return {
      global: true,
      secret: jwtConfig?.secret,
      signOptions: {
        expiresIn: (jwtConfig?.expiresIn || '7d') as StringValue | number,
        issuer: jwtConfig?.issuer || 'life-record-api',
        audience: jwtConfig?.audience || 'life-record-client',
        algorithm,
      },
      verifyOptions: {
        issuer: jwtConfig?.issuer || 'life-record-api',
        audience: jwtConfig?.audience || 'life-record-client',
      },
    };
  },
});
